package com.zbs.framework.dao.utils.jpa;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * 分页工具接口
 */
public interface PageUtil {

    /**
     * 获取Pageable
     * @param pageIndex 前端从1开始
     * @param pageSize
     * @return
     */
    static Pageable getPageable(Integer pageIndex, Integer pageSize){
        return getPageable(pageIndex, pageSize, null);
    }


    /**
     * 获取Pageable
     * @param pageIndex 前端从1开始
     * @param pageSize
     * @return
     */
    static Pageable getPageable(Integer pageIndex, Integer pageSize, Sort sort){
        Pageable pageable = null;
        if (pageIndex != null && pageSize != null){
            if (pageIndex < 1) {
                pageIndex = 0;
            } else {
                pageIndex --;
            }

            if (pageSize < 1) {
                pageSize = 10;
            }

        } else {

            pageIndex = 0;
            pageSize = Integer.MAX_VALUE;

        }

        if (sort != null) {
            pageable = PageRequest.of(pageIndex, pageSize, sort);
        } else {
            pageable = PageRequest.of(pageIndex, pageSize);
        }

        return pageable;
    }

    static Pageable setPageable(Pageable pageable, Sort sort){

        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);

        return pageable;
    }

}
